package com.dn.lotte.ui.usercenter.fragment;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.graphics.Color;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.dn.lotte.R;
import com.dn.lotte.api.ServerApi;
import com.dn.lotte.bean.BettingBean;
import com.dn.lotte.bean.EventBusBean;
import com.dn.lotte.ui.usercenter.activity.TnumberDetailsActivity;
import com.dn.lotte.ui.usercenter.adapter.BettingAdapter;
import com.dn.lotte.widget.CustomLoadMoreView;
import com.easy.common.base.BaseFragment;
import com.lzy.okgo.model.HttpParams;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.annotations.NonNull;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;

/**
 * ░░░░░░░░░░░░░░░░░░░░░░░░▄░░
 * ░░░░░░░░░▐█░░░░░░░░░░░▄▀▒▌░
 * ░░░░░░░░▐▀▒█░░░░░░░░▄▀▒▒▒▐
 * ░░░░░░░▐▄▀▒▒▀▀▀▀▄▄▄▀▒▒▒▒▒▐
 * ░░░░░▄▄▀▒░▒▒▒▒▒▒▒▒▒█▒▒▄█▒▐
 * ░░░▄▀▒▒▒░░░▒▒▒░░░▒▒▒▀██▀▒▌
 * ░░▐▒▒▒▄▄▒▒▒▒░░░▒▒▒▒▒▒▒▀▄▒▒
 * ░░▌░░▌█▀▒▒▒▒▒▄▀█▄▒▒▒▒▒▒▒█▒▐
 * ░▐░░░▒▒▒▒▒▒▒▒▌██▀▒▒░░░▒▒▒▀▄
 * ░▌░▒▄██▄▒▒▒▒▒▒▒▒▒░░░░░░▒▒▒▒
 * ▀▒▀▐▄█▄█▌▄░▀▒▒░░░░░░░░░░▒▒▒
 * 单身狗就这样默默地看着你，一句话也不说。
 * 投注记录
 *
 * @author DN
 * @data 2017/10/13
 **/
@SuppressLint("ValidFragment")
public class BettingFragment extends BaseFragment implements SwipeRefreshLayout.OnRefreshListener, BaseQuickAdapter.RequestLoadMoreListener {
    private String mTag;
    private int page = 1, pagesize = 10;
    private List<BettingBean.TableBean> mList = new ArrayList<>();
    private BettingAdapter mAdapter;
    private boolean mLoadMoreEndGone = false;
    private int isRefresh = 0;

    public BettingFragment(String tag) {
        this.mTag = tag;
    }

    @Bind(R.id.rv_list)
    RecyclerView mRecyclerView;
    @Bind(R.id.swipeLayout)
    SwipeRefreshLayout mSwipeLayout;

    @Override
    protected int getLayoutResource() {
        return R.layout.fragment_betting;
    }

    @Override
    public void initPresenter() {

    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    protected boolean mIsVisible = false;

    /**
     * 在这里实现Fragment数据的缓加载.
     */
    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        if (getUserVisibleHint()) {
            mIsVisible = true;
            onVisible();
        } else {
            mIsVisible = false;
            onInvisible();
        }
    }

    protected void onInvisible() {
    }

    /**
     * 显示时加载数据,需要这样的使用
     * 注意声明 isPrepared，先初始化
     * 生命周期会先执行 setUserVisibleHint 再执行onActivityCreated
     * 在 onActivityCreated 之后第一次显示加载数据，只加载一次
     */
    protected void onVisible() {
        loadData();
    }

    @Override
    protected void initView() {
        if (!EventBus.getDefault().isRegistered(this))
            EventBus.getDefault().register(this);

        mSwipeLayout.setColorSchemeColors(Color.rgb(147, 147, 147));
        mSwipeLayout.setOnRefreshListener(this);
        mRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
        mAdapter = new BettingAdapter(R.layout.item_betting, mList);
        CustomLoadMoreView mLoadMoreView = new CustomLoadMoreView();
        mAdapter.setLoadMoreView(mLoadMoreView);
        mAdapter.setOnLoadMoreListener(this, mRecyclerView);
        mAdapter.openLoadAnimation(BaseQuickAdapter.SCALEIN);
        mAdapter.isFirstOnly(false);
//        mLoadMoreEndGone = true;
        mRecyclerView.setAdapter(mAdapter);
        isRefresh = 0;

        mAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                Intent intent = new Intent(getActivity(), TnumberDetailsActivity.class);
                intent.putExtra("tdetails", mAdapter.getData().get(position));
                startActivity(intent);
            }
        });
    }

    private void loadData() {
        HttpParams httpParams = new HttpParams();
        httpParams.put("page", page);
        httpParams.put("pagesize", pagesize);
        httpParams.put("d1", "");
        httpParams.put("d2", "");
        httpParams.put("lid", "");
        httpParams.put("state", mTag);
        httpParams.put("sel", "");
        httpParams.put("u", "");
        ServerApi.getBettingData(httpParams)
                .doOnSubscribe(new Consumer<Disposable>() {
                    @Override
                    public void accept(@NonNull Disposable disposable) throws Exception {
//                        startProgressDialog();
                    }
                })
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<BettingBean>() {
                    @Override
                    public void onSubscribe(@NonNull Disposable d) {
                        if (mSwipeLayout != null) mSwipeLayout.setRefreshing(true);
                    }

                    @Override
                    public void onNext(@NonNull BettingBean purchaseBean) {
                        if (purchaseBean.getResult().equals("1")) {
                            Log.i("DNlog", purchaseBean.getTable().size() + "");

                            if (isRefresh == 1) {
                                mAdapter.loadMoreComplete();
                                mAdapter.addData(purchaseBean.getTable());
                            } else {
                                if (mSwipeLayout != null) mSwipeLayout.setRefreshing(false);
                                mAdapter.setNewData(purchaseBean.getTable());
                            }
                            if (purchaseBean.getTable().size() < pagesize) {
                                mAdapter.loadMoreEnd(true);
                            }
                        }
                    }

                    @Override
                    public void onError(@NonNull Throwable e) {
                        if (mSwipeLayout != null) mSwipeLayout.setRefreshing(false);

                    }

                    @Override
                    public void onComplete() {
                        stopProgressDialog();
                    }
                });
    }

    @Override
    public void onRefresh() {
        isRefresh = 0;
        page = 1;
        loadData();
    }

    @Override
    public void onLoadMoreRequested() {
        isRefresh = 1;
        page++;
        loadData();
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMainEventBus(EventBusBean<String> bean) {
        if ("cedansuccess".equals(bean.getTag())) {
            isRefresh = 0;
            page = 1;
            loadData();
        }
    }
}
